package com.dy.线性表.链表;

import com.dy.线性表.Ilist;

import java.util.Scanner;

public class LinkList implements Ilist {
    public Node head;

    public LinkList() {
        head = new Node();
    }
    //order控制头插法和尾插法，order==1，尾插
    public LinkList(int n , boolean order) throws Exception {
        this();
        if(order){
            createTail(n);
        }
        else createHead(n);
    }
    public void createTail(int n ) throws Exception {
        Scanner sc = new Scanner(System.in);
        for(int j =0 ; j<n;j++){
            insert(length(),sc.next());
        }

    }
    public void createHead(int n) throws Exception {
        Scanner sc = new Scanner(System.in);
        for(int j =0 ; j<n;j++){
            insert(0,sc.next());
        }
    }


    @Override
    public void clear() {
        head.next=null;
        head.data=null;
    }

    //判断带头节点的单链表是否为空，头节点不存值
    @Override
    public boolean isEmpty() {
        return head.next==null ;
    }

    @Override
    //带头节点的链表长度，head不算长度
    public int length() {
        int len = 0;
        Node p = head.next;
        while(p!=null){
            len++;
            p=p.next;
        }
        return len;
    }

    @Override
    public Object get(int i) throws Exception {
        Node p = head.next;
        int j=0;
        while(p!=null && j<i){
            p=p.next;
            j++;
        }
        if(p==null||j>i){
            throw new Exception(("第"+i+"个元素不存在"));
        }
        return p.data;
    }

    @Override
    public void insert(int i, Object x) throws Exception {
        Node p = head;
        int j =0;
        while(j<i &&p!=null){

            p = p.next;
            j++;
        }
        if(j!=i){
            throw new Exception("ｉ不合法");
        }
        Node s = new Node(x);
        s.next = p.next;
        p.next = s;

    }

    @Override
    public void remove(int i) throws Exception {
        Node p =head;
        int j=0;
        while(j<i &&p!=null){
            j++;
            p=p.next;
        }
        if( j!=i){
            throw new Exception("ｉ不合法");
        }
        p.next = p.next.next;

    }

    @Override
    public int indexOf(Object x) {
        Node p = head.next;
        int j =0;
        while(p!=null){
            if(p.equals(x)){
                return j;
            }
            p=p.next;
            j++;
        }
        return -1;
    }

    //带头结点的遍历
    @Override
    public void display() {
        Node p = head.next;
        while(p!=null){
            System.out.print(p.data+" ");
            p=p.next;
        }
        System.out.println();
    }
}
